// dh-purchase_requests 云对象 - 采购申请管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-purchase_requests] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-purchase_requests] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch', 'approve', 'reject'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	async getPurchaseRequestById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '采购申请ID不能为空');
			}

			const res = await db.collection('dh-purchase_requests').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '采购申请不存在');
			}
			return formatResponse(200, res.data[0]);
		} catch (error) {
			return formatError(error, '获取采购申请失败');
		}
	},

	async listPurchaseRequests(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 默认不显示已删除记录
			query.is_deleted = false;
			
			const res = await db.collection('dh-purchase_requests')
				.where(query)
				.skip(skip)
				.limit(limit)
				.orderBy('create_time', 'desc')
				.get();

			// 获取所有申请人ID
			const requesterIds = [...new Set(res.data.map(item => item.requester_id).filter(id => id))];
			
			// 查询申请人信息
			let usersMap = {};
			if (requesterIds.length > 0) {
				const usersRes = await db.collection('uni-id-users')
					.where({ _id: _.in(requesterIds) })
					.field({ _id: true, username: true, nickname: true, realname_auth: true })
					.get();

				usersRes.data.forEach(user => {
					const realName = user.realname_auth?.real_name || '';
					usersMap[user._id] = {
						real_name: realName,
						nickname: user.nickname || '',
						username: user.username || ''
					};
				});
			}

			// 组装数据，为每个item添加采购类型文本
			const dataWithUsers = res.data.map(request => {
				const userInfo = usersMap[request.requester_id];
				const itemTypeText = request.item_type === 1 ? '对外销售' : request.item_type === 2 ? '内部使用' : '未知';
				return {
					...request,
					requester_info: userInfo || { real_name: '', nickname: '', username: '' },
					item_type_text: itemTypeText
				};
			});

			return formatResponse(200, dataWithUsers, 'success', { count: dataWithUsers.length });
		} catch (error) {
			return formatError(error, '获取采购申请列表失败');
		}
	},

	async createPurchaseRequest(data) {
		try {
		if (!data.items || data.items.length === 0) {
			return formatResponse(400, null, '采购项目不能为空');
		}

		const totalAmount = data.items.reduce((sum, item) => sum + (item.quantity * item.unit_price), 0);
		const requestNumber = 'PR' + Date.now();

		let requestData = {
				request_number: requestNumber,
				requester_id: data.requester_id || '',
				requester_name: data.requester_name || '',
				items: data.items,
				total_amount: totalAmount,
				status: data.status || 'pending',
				priority: data.priority || 'normal',
				supplier: data.supplier || '',
				delivery_date: data.delivery_date || '',
				notes: data.notes || '',
				attachments: data.attachments || [],
				approver_id: data.approver_id || '',
				approval_time: null,
				rejection_reason: '',
				is_deleted: false,  // 软删除字段，默认未删除
			create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		requestData = await autoMountHospitalId(requestData);

		const res = await db.collection('dh-purchase_requests').add(requestData);
			return formatResponse(201, { _id: res.id }, '采购申请创建成功');
		} catch (error) {
			return formatError(error, '创建采购申请失败');
		}
	},

	async updatePurchaseRequest(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '采购申请ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-purchase_requests').doc(id).update(updateData);
			return formatResponse(200, null, '采购申请更新成功');
		} catch (error) {
			return formatError(error, '更新采购申请失败');
		}
	},

	async deletePurchaseRequest(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '采购申请ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-purchase_requests', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '采购申请已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除采购申请失败');
		}
	},

	async batchUpdatePurchaseRequests(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-purchase_requests').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	async batchDeletePurchaseRequests(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-purchase_requests', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	async approvePurchaseRequest(id, approverId, approverName) {
		try {
			if (!id) {
				return formatResponse(400, null, '采购申请ID不能为空');
			}

			await db.collection('dh-purchase_requests').doc(id).update({
				status: 'approved',
				approver_id: approverId,
				approver_name: approverName,
				approval_time: Date.now(),
				update_time: Date.now()
			});

			return formatResponse(200, null, '采购申请已批准');
		} catch (error) {
			return formatError(error, '批准采购申请失败');
		}
	},

	async rejectPurchaseRequest(id, rejectionReason) {
		try {
			if (!id) {
				return formatResponse(400, null, '采购申请ID不能为空');
			}

			await db.collection('dh-purchase_requests').doc(id).update({
				status: 'rejected',
				rejection_reason: rejectionReason || '',
				update_time: Date.now()
			});

			return formatResponse(200, null, '采购申请已拒绝');
		} catch (error) {
			return formatError(error, '拒绝采购申请失败');
		}
	},

	async getPendingApprovals(hospitalId) {
		try {
			if (!hospitalId) {
				return formatResponse(400, null, '医院ID不能为空');
			}

			const res = await db.collection('dh-purchase_requests')
				.where({ hospital_id: hospitalId, status: 'pending' })
				.orderBy('create_time', 'desc')
				.get();

			return formatResponse(200, res.data, 'success', { count: res.data.length });
		} catch (error) {
			return formatError(error, '获取待审批采购申请失败');
		}
	}
};
